package util;

import java.sql.*;

public class BaseDao {
    private String url = "jdbc:mysql://localhost:3306/qmm?serverTimezone=GMT-8";
    private String root = "root";
    private String pwd = "root";

    public Connection conn;
    public PreparedStatement ps;
    public ResultSet rs;

    static{
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void getConnection() {
        try {
            conn = DriverManager.getConnection(url, root, pwd);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void closeAll() {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public ResultSet exeQ(String sql, Object... obj) {
        getConnection();
        try {
            ps = conn.prepareStatement(sql);
            if (obj != null) {
                for (int i = 0; i < obj.length; i++) {
                    ps.setObject(i+1,obj[i]);
                }
            }
            rs = ps.executeQuery();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rs;
    }


    public int exeU(String sql, Object... obj) {
        getConnection();
        int shu = 0;
        try {
            ps = conn.prepareStatement(sql);
            if (obj != null) {
                for (int i = 0; i < obj.length; i++) {
                    ps.setObject(i+1,obj[i]);
                }
            }
            shu = ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return shu;
    }


}
